#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Root Privilege Maintenance Assistant - 演示脚本
展示系统的主要功能和跨平台兼容性
"""

import sys
import os
import platform

# 添加模块路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'modules'))

def show_banner():
    """显示横幅"""
    banner = """
    ╔══════════════════════════════════════════════════════════════╗
    ║                Root Privilege Maintenance Assistant          ║
    ║                        演示系统                              ║
    ╠══════════════════════════════════════════════════════════════╣
    ║  功能展示:                                                   ║
    ║  • 一键集成部署                                              ║
    ║  • 跨平台兼容性                                              ║
    ║  • 痕迹清理验证                                              ║
    ║  • 后门检查                                                  ║
    ║  • 环境检测                                                  ║
    ╚══════════════════════════════════════════════════════════════╝
    """
    print(banner)

def demo_environment_detection():
    """演示环境检测功能"""
    print("\n" + "="*60)
    print("1. 环境检测演示")
    print("="*60)
    
    try:
        from environment.detector import KernelDetector, EnvironmentAnalyzer
        from environment.container_detector import ContainerEnvironmentDetector
        from environment.cloud_detector import CloudEnvironmentDetector
        
        print(f"[*] 当前操作系统: {platform.system()}")
        print(f"[*] 系统版本: {platform.release()}")
        print(f"[*] 架构: {platform.machine()}")
        
        # 内核检测
        kernel_detector = KernelDetector()
        kernel_info = kernel_detector.detect_kernel_version()
        print(f"[*] 内核版本: {kernel_info.get('release', 'Unknown')}")
        
        # 容器检测
        container_detector = ContainerEnvironmentDetector()
        is_container = container_detector.is_container()
        print(f"[*] 容器环境: {'是' if is_container else '否'}")
        
        # 云环境检测
        cloud_detector = CloudEnvironmentDetector()
        cloud_provider = cloud_detector.detect_cloud_provider()
        print(f"[*] 云服务提供商: {cloud_provider if cloud_provider else '本地环境'}")
        
        # 环境分析
        env_analyzer = EnvironmentAnalyzer()
        analysis = env_analyzer.full_analysis()
        print(f"[*] 环境分析完成，发现 {len(analysis.get('capabilities', {}))} 项能力")
        
        print("[✓] 环境检测完成")
        
    except Exception as e:
        print(f"[!] 环境检测失败: {e}")

def demo_backdoor_checks():
    """演示后门检查功能"""
    print("\n" + "="*60)
    print("2. 后门检查演示")
    print("="*60)
    
    try:
        from persistence import backdoor_checks
        
        print("[*] 执行后门检查...")
        
        # 检查系统信息
        print("[*] 检查系统信息...")
        system_info = backdoor_checks.check_system_info()
        print(f"    - 内核版本: {system_info.get('kernel_version', 'N/A')}")
        print(f"    - 架构: {system_info.get('architecture', 'N/A')}")
        
        # 检查crontab
        print("[*] 检查计划任务...")
        crontab_result = backdoor_checks.check_crontab()
        print(f"    - 状态: {'正常' if crontab_result.get('status') == 'success' else '异常'}")
        
        # 检查进程监控
        print("[*] 检查进程监控...")
        strace_result = backdoor_checks.check_strace()
        print(f"    - 监控进程: {'发现' if strace_result.get('found') else '未发现'}")
        
        # 检查SSH配置
        print("[*] 检查SSH配置...")
        ssh_result = backdoor_checks.check_ssh_config()
        print(f"    - SSH状态: {ssh_result.get('status', 'Unknown')}")
        
        print("[✓] 后门检查完成")
        
    except Exception as e:
        print(f"[!] 后门检查失败: {e}")

def demo_trace_verification():
    """演示痕迹验证功能"""
    print("\n" + "="*60)
    print("3. 痕迹清理验证演示")
    print("="*60)
    
    try:
        from cleaner.verify import TraceVerifier
        
        verifier = TraceVerifier()
        
        # 模拟清理目标
        cleanup_targets = {
            'logs': ['/tmp/demo.log', 'C:\\Temp\\demo.log'],
            'processes': ['demo_process'],
            'files': ['/tmp/demo_file', 'C:\\Temp\\demo_file'],
            'network': [],
            'system': []
        }
        
        print("[*] 执行痕迹清理验证...")
        result = verifier.verify_cleanup_effectiveness(cleanup_targets)
        
        print(f"[*] 发现痕迹数量: {result['total_traces_found']}")
        print(f"[*] 清理效果: {result['cleanup_effectiveness']:.2f}%")
        print(f"[*] 建议数量: {len(result['recommendations'])}")
        
        print("[✓] 痕迹验证完成")
        
    except Exception as e:
        print(f"[!] 痕迹验证失败: {e}")

def demo_one_click_integration():
    """演示一键集成功能"""
    print("\n" + "="*60)
    print("4. 一键集成演示")
    print("="*60)
    
    try:
        from automation.one_click_integration import OneClickIntegration
        
        integration = OneClickIntegration()
        
        print("[*] 显示集成菜单...")
        integration.show_menu()
        
        print("\n[*] 检测环境...")
        env_info = integration.detect_environment()
        print(f"    - 操作系统: {env_info.get('os', 'Unknown')}")
        print(f"    - 权限级别: {env_info.get('privilege_level', 'Unknown')}")
        
        print("\n[*] 生成部署策略...")
        strategy = integration.generate_strategy(env_info)
        print(f"    - 策略类型: {strategy.get('type', 'Unknown')}")
        print(f"    - 步骤数量: {len(strategy.get('steps', []))}")
        
        print("[✓] 一键集成演示完成")
        
    except Exception as e:
        print(f"[!] 一键集成演示失败: {e}")

def demo_cross_platform_compatibility():
    """演示跨平台兼容性"""
    print("\n" + "="*60)
    print("5. 跨平台兼容性演示")
    print("="*60)
    
    current_os = platform.system()
    print(f"[*] 当前平台: {current_os}")
    
    # 展示平台特定的命令
    if current_os == 'Windows':
        print("[*] Windows平台特性:")
        print("    - 使用PowerShell命令")
        print("    - 支持Windows服务检查")
        print("    - 兼容Windows路径格式")
        print("    - 支持注册表操作")
    elif current_os == 'Linux':
        print("[*] Linux平台特性:")
        print("    - 使用标准Unix命令")
        print("    - 支持systemd服务")
        print("    - 兼容Linux文件系统")
        print("    - 支持crontab操作")
    else:
        print(f"[*] {current_os}平台特性:")
        print("    - 基础跨平台支持")
        print("    - 标准命令兼容")
    
    print("[✓] 跨平台兼容性展示完成")

def main():
    """主演示函数"""
    show_banner()
    
    print(f"\n[*] 系统信息:")
    print(f"    - Python版本: {sys.version.split()[0]}")
    print(f"    - 操作系统: {platform.system()} {platform.release()}")
    print(f"    - 架构: {platform.machine()}")
    
    try:
        # 运行各个演示
        demo_environment_detection()
        demo_backdoor_checks()
        demo_trace_verification()
        demo_one_click_integration()
        demo_cross_platform_compatibility()
        
        print("\n" + "="*60)
        print("演示完成！")
        print("="*60)
        print("[✓] 所有功能模块演示成功")
        print("[✓] 跨平台兼容性验证通过")
        print("[✓] 系统集成测试完成")
        
    except KeyboardInterrupt:
        print("\n[!] 演示被用户中断")
    except Exception as e:
        print(f"\n[!] 演示过程中发生错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()